<?php

namespace App\Backend\Service;

use App\Models\Doubanpost;
use App\Exceptions\InvalidRequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Backend\Service\BaseService;
use App\Http\Service\PythonService;
class DoubanPushService extends BaseService
{

    private $model;

    public function __construct(Doubanpost $model,PythonService $pythonService)
    {
        parent ::__construct();
        $this->model = $model;
        $this->pythonService=$pythonService;
    }
    public function checkURL($url, $target) {
        // 使用正则表达式检测URL中是否包含目标字符串
        if (preg_match('/' . preg_quote($target, '/') . '/', $url)) {
            return true;
        } else {
            return false;
        }
    }
    // 从URL中提取数字ID
    public  function extractIdFromUrl($url) {
        // 方法1: 使用正则表达式直接匹配数字
        if (preg_match('/\/(\d+)\.html$/', $url, $matches)) {
            return $matches[1];
        }
        
        // 方法2: 如果方法1失败，尝试提取最后一个斜杠后的数字
        if (preg_match('/(\d+)(?=\.html$|$)/', $url, $matches)) {
            return $matches[1];
        }
        
        return false;
    }

      /**
     * 添加
     */
    public function add($request,$data)
    {

       $data['images']=[];
       $contents=$data['contents'];
       unset($data['contents']);
       $new_content=[];

       $target="https://news.ixbk.fun";
       $guanlian_shop_arr=[];
       foreach ($contents as $key => $val) {
            if($val['type']=='text'){
                $new_content[]=[
                    'type'=>$val['type'],
                    'content'=>$val['content'],
                ];
            }
            #获取文章链接
            if($val['type']=='linked_article'){
                $content=$val['content'];
                $group_name=$content['group_name'];
                if($group_name=='买组'){
                    $group_type=3;
                }
                if($group_name=='拼租'){
                    $group_type=4;
                }


                $hdata1 = [
                    'user_id'=>0,
                    'cover'=>'',//默认取第一张图片
                    'content_books'=>[],
                    'title'=>$content['title'],
                    'nickname'=>$content['userName'],
                    'unique_id'=>$content['id'],
                    'publish_time'=>$content['publicTime'],
                    'avatar'=>$content['avatar'],
                    'group_type'=>$group_type,
                    'contents'=>$content['contents'],
                    'article_url'=>$content["url"],
                    'images'=>[],
                    'channel'=>'豆瓣',
                    'like_count'=>'0',
                    'collect_count'=>'0',
                    'comment_count'=>'0',
                    'view_count'=>'0',
                    'status'=>'1',
                    'is_delete'=>'2', //是否删除 1  删除  2 不删除
                ];

              

                if(empty($hdata1['content_books'])){
                    $hdata1['content_books']=[];
                }
                if(empty($hdata1['images'])){
                    $hdata1['images']=[];
                }
                
               // dd($hdata1);
                $this->add($request,$hdata1);
            }

            if($val['type']=='link'){
                $url=$val['url'];
                #跳转到内部链接
                if ($this->checkURL($url, $target)){
                    $extractId=$this->extractIdFromUrl($url);
                    $new_content[]=[
                        'type'=>'onelink',
                        'unique_id'=>$extractId,
                        'content'=>$val['content'],
                    ];
                }else{
                    #普通链接地址
                    $hdata=[
                        'shop_buy_url'=>$val['url']
                    ];
                    //dd($hdata);
                    $goods_detail=$this->pythonService->fetch_url_goods_detail($request,$hdata,$is_zdm=false);
                    //dd($goods_detail);
                    if($goods_detail){
                        $new_content[]=  [
                                "type"=> "link",
                                "text"=> $goods_detail['productUrl'],
                                "title"=> $goods_detail['title'],
                                "productImage"=>$goods_detail['productImage'],
                                "productName"=> $goods_detail['productName'],
                                "product_id"=> $goods_detail['productId'],
                                "platform_name"=>$goods_detail['productUrl'],
                                "link_text"=> $val['url']
                        ];
                    }else{
                         $new_content[]=  [
                                "type"=> "text",
                                "text"=> $val['url']
                        ];
                    }
                   
                
                }
                
                
            }

            if($val['type']=='image'){
                $images[]=$val['url'];
            }
        }
        if(!empty($images)){
            $cover=$images[0];
            $data['cover']=$cover;
        }

        $jsonData = $request->json()->all();
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);

        $data['create_time']=date("Y-m-d H:i:s");
        #组装关联商品
        $guanlian_shop_arr=[];
        foreach($new_content as $k1=>$v1){
            if($v1['type']=='link'&&$v1['product_id'] &&$v1['productImage']){
                $productUnique=platform_name_product_id($v1['platform_name'],$v1['product_id']);
                //dd($productUniqueId);
                $guanlian_shop_arr[]=[
                    "platformName"=>$v1['platform_name'],
                    "productId"=>$v1['product_id'],
                    "image"=>$v1['productImage'],
                    "title"=>$v1['title'],
                    "productUniqueId"=>$productUnique['1'],
                    "create_time"=>$data['create_time'],
                ];
               // dd($v1);
            }

        }
        if(!empty($guanlian_shop_arr)){
            $guanlian_shop_arr=array_values($guanlian_shop_arr);
        }
        $guanlian_shop_arr = json_encode($guanlian_shop_arr, JSON_UNESCAPED_UNICODE);

        //dd($guanlian_shop_arr);
        $data['guanlian_shop']=$guanlian_shop_arr;
        $data['content_books']=$new_content;
        $data['content_books'] = json_encode($data['content_books'], JSON_UNESCAPED_UNICODE);
        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        //dd($data['guanlian_shop']);
        $first=$this->model->where(['unique_id'=>$data['unique_id']])->first();
        if($first){
            $post_info=$this->model->where(['unique_id'=>$data['unique_id']])->update($data);
        }else{
            $data['update_time'] =date("Y-m-d H:i:s");
            $post_id=$this->model->insertGetId($data);
        }
        
        

    }

   


}
